package com.hll.servlet;

import com.Constants;
import com.hll.model.Book;
import com.hll.model.BookStatus;
import com.hll.model.Pagination;
import com.hll.model.User;
import com.hll.service.BookService;
import com.hll.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/myBook.action")
public class ShowMyBookServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        HttpSession session = request.getSession();
        User user = (User)session.getAttribute(Constants.USER);

        String status = request.getParameter("status");
        if (StringUtil.isEmpty(status)) {
            status = "all";
        }

        //取当前页码，若为空，则默认显示第一页/
        String currentPageStr = request.getParameter("currentPage");
        if (StringUtil.isEmpty(currentPageStr)) {
            currentPageStr = "1";
        }
        int currentPage = Integer.parseInt(currentPageStr);
        if (currentPage < 1) {
            currentPage = 1;
        }

        Pagination pagination = new Pagination();
        pagination.setCurrentPage(currentPage);

        BookService bookService = new BookService();
        BookStatus statusEnum = null;
        try {
            statusEnum = BookStatus.valueOf(status);
        } catch (Exception e) {
            statusEnum = BookStatus.valueOf("all");
        }

        //查询不同状态的图书
        List<Book> books = bookService.query(user.getId(), statusEnum, pagination);

        request.setAttribute("status", status);
        request.setAttribute("books", books);
        request.setAttribute("pagination", pagination);

        //遍历不同状态的本总数，动态显示我的全部图书数量
        for (BookStatus enumStatus : BookStatus.values()) {
            int myBookCount = bookService.getMyBookCount(user.getId(), enumStatus);
            request.setAttribute(enumStatus + "Count", myBookCount);
        }

        request.getRequestDispatcher("/WEB-INF/jsp/book/myBook.jsp").forward(request, response);
    }
}
